package cn.hfatec.shms.web.yk.ykTj.service;

import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.base.BaseDao;
import cn.hfatec.constants.SysContant;
import cn.hfatec.shms.advice.annotation.MysqlDataSource;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.constants.ShmsProperties;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.enums.KeyTypeEnum;
import cn.hfatec.shms.exception.KeyGenException;
import cn.hfatec.shms.exception.NotAuthException;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.system.organization.model.Organization;
import cn.hfatec.shms.system.organization.service.OrganizationService;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.utils.ExcelUtil;
import cn.hfatec.shms.utils.KeyGenUtils;
import cn.hfatec.shms.web.yk.ykGather.model.YkGather;
import cn.hfatec.shms.web.yk.ykGather.service.YkGatherService;
import cn.hfatec.shms.web.yk.ykTj.dao.YkTjDao;
import cn.hfatec.shms.web.yk.ykTj.model.YkCheck;
import cn.hfatec.shms.web.yk.ykTj.model.YkTj;
import cn.hfatec.shms.web.yk.ykTj.model.YkTjParams;
import com.google.common.base.Optional;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author hfatec
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Service("YkTjService")
public class YkTjService {

    public static final String BEAN_ID = "YkTjService";

    //注入Dao层
    @Resource(name = "YkTjDao")
    private YkTjDao ykTjDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;
    @Resource(name = "shmsProperties")
    private ShmsProperties shmsProperties;

    //服务层
    @Resource(name = "OrganizationService")
    private OrganizationService organizationService;
    //服务层
    @Resource(name = "YkGatherService")
    private YkGatherService ykGatherService;

    @Transactional
    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     * 查询数据
     *
     * @param ykTjParams
     * @param page
     */
    @Transactional
    public Table queryYkTjTable(YkTjParams ykTjParams, Page page) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", ykTjParams);
        return baseDao.queryTableByPage("queryYkTj", params, page);
    }

    /**
     * 查询数据
     *
     * @param ykTjParams
     *
     */
    @Transactional
    public YkTj hjYkTjTable(YkTjParams ykTjParams) {


        return ykTjDao.hjYkTj(ykTjParams);
    }

    /**
     * 插入数据
     *
     * @param ykTj
     */
    @Transactional
    public String saveYkTj(YkTj ykTj, User user) throws KeyGenException {
        if (ykTj.getId() != null) {
            YkTj result = getYkTj(ykTj.getId());
            if (result != null) {
                ykGatherService.deleteYkGather(result.getTjId());
                String[] payments = null;
                if (ykTj.getPayment() != null) {
                    String payment = ykTj.getPayment().replace("，", ",") + ",";
                    if (StringUtils.isNotBlank(payment)) {
                        if (payment.contains(",")) {

                    }payments = payment.split(",");
                }
                }
                String[] sprices = null;
                if (ykTj.getSprice() != null) {
                    String sprice = ykTj.getSprice().replace("，", ",") + ",";
                    if (StringUtils.isNotBlank(sprice)) {
                        if (sprice.contains(",")) {
                            sprices = sprice.split(",");
                        }
                    }
                }
                if (payments.length != sprices.length) {
                    return new JsonResponse(JsonResponse.RETURN_FAILURE, "收款方式和收款金额个数不等").toString();

                }
                YkGather ykGather = new YkGather();
                for (int i = 0; i < payments.length; i++) {
                    ykGather.setBillId(result.getTjId());
                    ykGather.setGatherType(payments[i]);
                    ykGather.setGatherMoney(sprices[i]);
                    ykGatherService.saveYkGather(ykGather);
                }
                ykTjDao.update(ykTj);
            } else {

                ykTj.setTjId(KeyGenUtils.createKeyByType(KeyTypeEnum.TJ_KEY));
                String[] payments = null;
                if (ykTj.getPayment() != null) {
                    String payment = ykTj.getPayment().replace("，", ",") + ",";
                    if (StringUtils.isNotBlank(payment)) {
                        if (payment.contains(",")) {
                            payments = payment.split(",");
                        }
                    }
                }
                String[] sprices = null;
                if (ykTj.getSprice() != null) {
                    String sprice = ykTj.getSprice().replace("，", ",") + ",";
                    if (StringUtils.isNotBlank(sprice)) {
                        if (sprice.contains(",")) {
                            sprices = sprice.split(",");
                        }
                    }
                }
                if (payments.length != sprices.length) {
                    return new JsonResponse(JsonResponse.RETURN_FAILURE, "收款方式和收款金额个数不等").toString();

                }
                YkGather ykGather = new YkGather();
                for (int i = 0; i < payments.length; i++) {
                    ykGather.setBillId(ykTj.getTjId());
                    ykGather.setGatherType(payments[i]);
                    ykGather.setGatherMoney(sprices[i]);
                    ykGatherService.saveYkGather(ykGather);
                }
                ykTj.setCreateTime(new Date());
                ykTj.setCreateName(user.getLoginName());
                ykTjDao.insert(ykTj);
            }
        } else {
            ykTj.setTjId(KeyGenUtils.createKeyByType(KeyTypeEnum.TJ_KEY));
            String[] payments = null;

            if (ykTj.getPayment() != null) {
                String payment = ykTj.getPayment().replace("，", ",") + ",";
                if (StringUtils.isNotBlank(payment)) {
                    if (payment.contains(",")) {
                        payments = payment.split(",");
                    }
                }
            }
            String[] sprices = null;
            if (ykTj.getSprice() != null) {
                String sprice = ykTj.getSprice().replace("，", ",") + ",";
                if (StringUtils.isNotBlank(sprice)) {
                    if (sprice.contains(",")) {
                        sprices = sprice.split(",");
                    }
                }
            }
            if (payments.length != sprices.length) {
                return new JsonResponse(JsonResponse.RETURN_FAILURE, "收款方式和收款金额个数不等").toString();

            }
            YkGather ykGather = new YkGather();
            for (int i = 0; i < payments.length; i++) {
                ykGather.setBillId(ykTj.getTjId());
                ykGather.setGatherType(payments[i]);
                ykGather.setGatherMoney(sprices[i]);
                ykGatherService.saveYkGather(ykGather);
            }
            ykTj.setCreateTime(new Date());
            ykTj.setCreateName(user.getLoginName());
            ykTjDao.insert(ykTj);
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 删除数据
     *
     * @param id
     */
    @Transactional
    public void deleteYkTj(Integer id) {
        YkTj ykTj=getYkTj(id);
        if(ykTj!=null)
        {
            ykGatherService.deleteYkGather(ykTj.getTjId());
        }
        ykTjDao.delete(id);
    }

    /**
     * 删除数据
     *
     * @param ykTjList
     */
    @Transactional
    public void deleteYkTjBatch(List<String> ykTjList) {
        for (String id : ykTjList) {
            deleteYkTj(Integer.valueOf(id));
        }
    }

    /**
     * 根据ID获取数据
     *
     * @param id
     */
    @Transactional
    public YkTj getYkTj(Integer id) {

        return ykTjDao.getYkTjById(id);
    }

    /**
     * 导入健康管理数据
     *
     * @param path
     * @param request
     * @param response
     * @return
     * @throws java.io.IOException
     */
    @Transactional
    @MysqlDataSource
    public String importCust(String path, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String filePath = path.substring(path.indexOf("/upload") + 7);
        User user = (User) request.getSession().getAttribute(ShmsConstant.LOGIN_USER_SESSION_NAME);
        Organization organization = new Organization();
        if (user == null) {
            throw new NotAuthException("用户未授权");
        } else {
            organization = organizationService.getOrganizationByOrgId(user.getOrgId());
        }
        String uploadPath = shmsProperties.getUploadPath();
        File file = new File(uploadPath + File.separator + filePath);
        boolean flag = false;
        String rule = "^1[358]\\d{9}$";
        String errorMsg = "";
        Workbook workbook = null;
        workbook = WorkbookFactory.create(file);
        Sheet sh = workbook.getSheetAt(0);//
        List<YkCheck> potentialCusts = this.buildCustWithAjaxUpload(sh);//
        if (potentialCusts != null && potentialCusts.size() > 0) {
            for (YkCheck ykCheck : potentialCusts) {
                //判读是否为有效数据
                if (ykCheck.isValid()) {
                    YkTj ykTj = ykCheck.getYkTj();
                    if (organization != null) {
                        ykTj.setOrgLevelCode(organization.getOrgLevelCode());
                    }
                    Optional<JsonResponse<String>> optional = checkCustByUniqueConstraint(ykTj);
                    if (optional.isPresent()) {
                        errorMsg += "第" + ykCheck.getRowNumber() + "收款方式和收款金额个数不等,不能导入!";
                        continue;
                    }
                    saveYkTj(ykTj, user);
                    flag = true;
                } else {//无效数据
                    errorMsg += "第" + ykCheck.getRowNumber() + "有错，不能导入!";
                }
            }
        } else {
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "导入的文件无符合数据").toString();
        }

        if (flag) {
            if ("".equals(errorMsg)) {
                return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "导入成功!" + errorMsg).toString();
            }
            return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "部分导入成功!" + errorMsg).toString();
        } else {
            return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "导入失败!" + errorMsg).toString();
        }

    }

    public Date luDate(String strDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 读取潜在客户导入的数据
     *
     * @param sh
     * @return
     * @throws Exception
     */
    @Transactional
    @MysqlDataSource
    private List<YkCheck> buildCustWithAjaxUpload(Sheet sh) throws Exception {
        List<YkCheck> checks = new ArrayList<YkCheck>();
        int rows = sh.getLastRowNum() + 1 - sh.getFirstRowNum(); // 总行数
        List<CodeInfo> sexList = CodeInfoCache.getCodeInfo(CodeType.SEX);
        List<CodeInfo> channelList = CodeInfoCache.getCodeInfo(CodeType.TKQD_TYPE);
        List<CodeInfo> AKList = CodeInfoCache.getCodeInfo(CodeType.AK_TYPE);
        ExcelUtil excelUtil = new ExcelUtil();
        for (int i = 1; i < rows; i++) {
            boolean flag = true;//数据是否有效(客户姓名，手机号存在)
            boolean flag2 = false;//判断是否该行有数据
            YkTj ykTj = new YkTj();
            YkCheck ykCheck = new YkCheck();
            ykCheck.setRowNumber(i + 1);
            ykCheck.setValid(true);
            String str = "";//下拉框
            // HSSFRow row = sh.getRow(i);//excel97-2003写法
            Row row = sh.getRow(i);
//            int cols = row.getLastCellNum() + 1 - row.getFirstCellNum(); // 该行的总列数
            Iterator cells = row.cellIterator();
            int j = 0;
            while (cells.hasNext()) {

//                HSSFCell cell = (HSSFCell) cells.next();//excel97-2003写法
                XSSFCell cell = (XSSFCell) cells.next();

                if (j == 0) {
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setBookId(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 1) {
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setCardId(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 2) {

                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setUserName(ExcelUtil.getStringRowCellValue(row, j));
                    }

                } else if (j == 3) {
                    // 年龄
                    str = excelUtil.getStringRowCellValue(row, j);
                    if (!StringUtils.isEmpty(str)) {
                        for (CodeInfo c : sexList) {
                            if (c.getContent().equals(str)) {
                                ykTj.setSex(c.getValue());
                            }
                        }
                    }

                } else if (j == 4) {
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setAge(ExcelUtil.getStringRowCellValue(row, j));
                    }// 性别
                } else if (j == 5) {
                    // 电话
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setSpareA(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 6) {
                    // 电话
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setPhone(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 7) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setIdentity(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 8) {
                    // 身份证

                    str = excelUtil.getStringRowCellValue(row, j);
                    if (!StringUtils.isEmpty(str)) {
                        for (CodeInfo c : AKList) {
                            if (c.getContent().equals(str)) {
                                ykTj.setAkType(c.getValue());
                            }
                        }
                    }

                } else if (j == 9) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getRowCellValueDate(row, j).toString())) {
                        ykTj.setBillTime(stringDate(excelUtil.getRowCellValueDate(row, j)));
                    }
                } else if (j == 10) {
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setProductName(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 11) {

                    str = excelUtil.getStringRowCellValue(row, j);
                    if (!StringUtils.isEmpty(str)) {
                        for (CodeInfo c : channelList) {
                            if (c.getContent().equals(str)) {
                                ykTj.setChannelType(c.getValue());
                            }
                        }
                    }
                } else if (j == 12) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setTjMoney(String.format("%.2f",Double.parseDouble(excelUtil.getStringRowCellValue(row, j))));
                    }
                } else if (j == 13) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setSsMoney(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 14) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setTjLj(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 15) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setTjDj(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 16) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setTjFg(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 17) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setPayment(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 18) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setSprice(excelUtil.getStringRowCellValue(row, j));
                    }
                }
                else if (j == 19) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykTj.setSpareB(excelUtil.getStringRowCellValue(row, j));
                    }
                }
                j++;
            }
            if (flag) {
//                 list.add(cust);
                ykCheck.setYkTj(ykTj);
                checks.add(ykCheck);
            } else {
//                TdCheck.setCustom(cust);
                if (flag2) {
                    checks.add(ykCheck);
                }
            }
        }
        return checks;
    }

    public String stringDate(Date billTime) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String sDate=sdf.format(billTime);
        return sDate;
    }

    /**
     * 根据客户姓名和手机查询唯一性
     *
     * @param ykTj
     * @return
     */
    @Transactional
    public Optional checkCustByUniqueConstraint(YkTj ykTj) {
        String payment = ykTj.getPayment().replace("，", ",");
        String sprice = ykTj.getSprice().replace("，", ",");
        int l = lenghtNum(payment);
        int s = lenghtNum(sprice);
        if (l != s) {
            return Optional.of(new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "收款方式和收款金额个数不等!"));
        }
        return Optional.absent();
    }

    public int lenghtNum(String lenghts) {
        int a = lenghts.length();
        String b = lenghts.replace(",", "");
        int c = b.length();
        return a - c;
    }

    /**
     * 导出
     *
     * @param
     */
    @Transactional
    public String exportExcel(YkTjParams ykTjParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            String clientFileName = encodeFilename(request, System.currentTimeMillis() + "");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName + ".xls");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            List dataList = ykTjDao.queryYkTj(ykTjParams);
            List nameList = new ArrayList();
            nameList.add("体检编号");
            nameList.add("预约号");
            nameList.add("卡号");
            nameList.add("客户姓名");
            nameList.add("性别");
            nameList.add("是否贵宾");
            nameList.add("类型");
            nameList.add("下单日期");
            nameList.add("产品名称");
            nameList.add("渠道类型");
            nameList.add("体检金额");
            nameList.add("实收金额");
            nameList.add("来捡");
            nameList.add("带检");
            nameList.add("分管");
            nameList.add("收款方式");
            nameList.add("收款金额");
            nameList.add("成本");
            this.exportExcel(nameList, dataList, os);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @return HSSFWorkbook
     */
    public HSSFWorkbook createWorkbook(List fieldName, List fieldData) {
        List<CodeInfo> sexList = CodeInfoCache.getCodeInfo(CodeType.SEX);
        List<CodeInfo> vipList = CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE);
        List<CodeInfo> jkglList = CodeInfoCache.getCodeInfo(CodeType.JKGL_TYPE);
        List<CodeInfo> channelList = CodeInfoCache.getCodeInfo(CodeType.TKQD_TYPE);
        List<CodeInfo> AKList = CodeInfoCache.getCodeInfo(CodeType.AK_TYPE);
        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("体检管理表");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCellStyle cellstyle = (HSSFCellStyle) wb.createCellStyle();// 设置表头样式
        cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
        cellstyle.setWrapText(true); // 设置为自动换行
        HSSFFont cellFont = (HSSFFont) wb.createFont(); // 创建表头字体样式
        cellFont.setFontHeightInPoints((short) 10); // 设置字体大小
        cellFont.setFontName("宋体"); // 设置字体类型
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        cellstyle.setFont(cellFont); // 为表头样式设置字体样式


        for (int i = 0; i < fieldName.size(); i++) {
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue((String) fieldName.get(i));
            cell.setCellStyle(cellstyle);
        }

        YkTj ykTj = null;

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        for (int i = 0; i < fieldData.size(); i++) {
            row = sheet.createRow(i + 1);
            ykTj = (YkTj) fieldData.get(i);
            // 第四步，创建单元格，并设置值

            if (ykTj.getTjId() == null) {
                row.createCell((short) 0).setCellValue("");
            } else {
                row.createCell((short) 0).setCellValue(ykTj.getTjId());
            }
            if (ykTj.getBookId() == null) {
                row.createCell((short) 1).setCellValue("");
            } else {
                row.createCell((short) 1).setCellValue(ykTj.getBookId());
            }
            if (ykTj.getCardId() == null) {
                row.createCell((short) 2).setCellValue("");
            } else {
                row.createCell((short) 2).setCellValue(ykTj.getCardId());
            }
            if (ykTj.getUserName() == null) {
                row.createCell((short) 3).setCellValue("");
            } else {
                row.createCell((short) 3).setCellValue(ykTj.getUserName());
            }
            if (ykTj.getSex() == null) {
                row.createCell((short) 4).setCellValue("");
            } else {
                for (CodeInfo c : sexList) {//汉化性别信息
                    if (c.getValue().equals(ykTj.getSex() + "")) {
                        row.createCell((short) 4).setCellValue(c.getContent());
                        break;
                    }
                }
            }
            if (ykTj.getSpareA() == null) {
                row.createCell((short) 5).setCellValue("");
            } else {
                row.createCell((short) 5).setCellValue(ykTj.getSpareA());
            }
            if (ykTj.getAkType() == null) {
                row.createCell((short) 6).setCellValue("");
            } else {

                for (CodeInfo c : AKList) {//汉化性别信息
                    if (c.getValue().equals(ykTj.getAkType() + "")) {
                        row.createCell((short) 6).setCellValue(c.getContent());
                        break;
                    }
                }

            }

            if (ykTj.getBillTime() == null) {
                row.createCell((short) 7).setCellValue("");
            } else {
                row.createCell((short) 7).setCellValue(ykTj.getBillTime());
            }
            if (ykTj.getProductName() == null) {
                row.createCell((short) 8).setCellValue("");
            } else {

                row.createCell((short) 8).setCellValue(ykTj.getProductName());
            }
            if (ykTj.getChannelType() == null) {
                row.createCell((short) 9).setCellValue("");
            } else {
                for (CodeInfo c : channelList) {//汉化性别信息
                    if (c.getValue().equals(ykTj.getChannelType() + "")) {
                        row.createCell((short) 9).setCellValue(c.getContent());
                        break;
                    }
                }

            }
            if (ykTj.getTjMoney() == null) {
                row.createCell((short) 10).setCellValue("");
            } else {
                row.createCell((short) 10).setCellValue(ykTj.getTjMoney());
            }
            if (ykTj.getSsMoney() == null) {
                row.createCell((short) 11).setCellValue("");
            } else {
                row.createCell((short) 11).setCellValue(ykTj.getSsMoney());
            }
            if (ykTj.getTjLj() == null) {
                row.createCell((short) 12).setCellValue("");
            } else {
                row.createCell((short) 12).setCellValue(ykTj.getTjLj());
            }
            if (ykTj.getTjDj() == null) {
                row.createCell((short) 13).setCellValue("");
            } else {
                row.createCell((short) 13).setCellValue(ykTj.getTjDj());
            }
            if (ykTj.getTjFg() == null) {
                row.createCell((short) 14).setCellValue("");
            } else {
                row.createCell((short) 14).setCellValue(ykTj.getTjFg());
            }
            if (ykTj.getPayment() == null) {
                row.createCell((short) 15).setCellValue("");
            } else {
                row.createCell((short) 15).setCellValue(ykTj.getPayment());
            }
            if (ykTj.getSprice() == null) {
                row.createCell((short) 16).setCellValue("");
            } else {
                row.createCell((short) 16).setCellValue(ykTj.getSprice());
            }
            if (ykTj.getCost() == null) {
                row.createCell((short) 17).setCellValue("");
            } else {
                row.createCell((short) 17).setCellValue(ykTj.getCost());
            }
        }
        //自适应列宽
        for (int i = 0; i < fieldName.size(); i++) {
            sheet.autoSizeColumn((short) i);
        }


        return wb;
    }


    //将信息写入输出流的方法。
    public void exportExcel(List fieldName, List fieldData, OutputStream os) throws Exception {
        HSSFWorkbook wb = createWorkbook(fieldName, fieldData);
        wb.write(os);
        os.close();
    }
}